package org.ragdollcat.first.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 普通文件上传
 */
@Service
@Slf4j
public class CommonFileUpload extends AbsFileUpload {
    /**
     * 处理文件来源
     *
     * @param source
     * @param file
     */
    @Override
    protected void processFile(Object source, File file) {
        MultipartFile multipartFile = ((MultipartFile) source);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验参数
     *
     * @param source
     */
    @Override
    protected void vaildParams(Object source) {
        MultipartFile multipartFile = ((MultipartFile) source);
        ThrowUtils.throwIf(ObjUtil.isEmpty(multipartFile), ErrorCode.PARAMS_ERROR, "'MultipartFile'不能为空");
        //校验大小
        final long standardSize = 1024 * 1024 * 2;
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > standardSize, ErrorCode.OPERATION_ERROR, "图片大小不能大于2MB");
        //校验格式
        //hutool工具包，根据文件名获取后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        List<String> standardFormat = Arrays.asList("jpg", "png", "webp", "jpeg");
        ThrowUtils.throwIf(!standardFormat.contains(suffix), ErrorCode.OPERATION_ERROR, "目前支持的图片格式：jpg，png，webp，jpeg");
    }

    /**
     * 得到原始文件名
     *
     * @param source
     * @return
     */
    @Override
    protected String getOriginalFilename(Object source) {
        MultipartFile multipartFile = ((MultipartFile) source);
        return multipartFile.getOriginalFilename();
    }
}
